package com.sdcqjy.mylibrary.http;

import com.sdcqjy.mylibrary.Logger;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by 52463 on 2018/3/23.
 * 下载访问
 */
public class DownloadHttp {
    private OkHttpClient okHttpClient;
    protected DownloadMode mode;
    private DownloadManage downloadManage;
    private Call call_;
    private int type;//0 完整下载，1 续传
    private boolean isStop;

    public DownloadHttp(DownloadMode mode) {
        //okHttpClient = HttpClient.getOkHttpClient();
        if (okHttpClient == null) {
            OkHttpClient.Builder builder = new OkHttpClient.Builder()
                    .connectTimeout(600, TimeUnit.SECONDS)
                    .dispatcher(HttpClient.getDispatcher());
            okHttpClient = builder.build();
        }
        this.mode = mode;
    }

    public DownloadHttp setDownloadManage(DownloadManage downloadManage) {
        this.downloadManage = downloadManage;
        return this;
    }

    public void start() {
        Request.Builder builder = new Request.Builder();
        //builder.addHeader("Dev", "Android");
        if (mode.currLen > 0) {
            type = 1;
            builder.addHeader("RANGE", "bytes=" + mode.currLen + "-");
        }
        Request build = builder.url(mode.url).build();
        //Request request = new Request.Builder().url(mode.url).build();
        call_ = okHttpClient.newCall(build);
        call_.enqueue(callback);//异步执行
    }

    public void stop() {
        //if (call_ != null) call_.cancel();
        isStop = true;
    }

    private Callback callback = new Callback() {
        public void onFailure(Call call, IOException e) {
            if (Logger.isDebug && e != null) e.printStackTrace();
            if (downloadManage != null) downloadManage.onError(mode);
        }

        public void onResponse(Call call, Response response) {
            try {
                if (response.isSuccessful()) {
                    File file = new File(mode.path);
                    if (!file.exists()) file.createNewFile();
                    long contentLength = response.body().contentLength();
                    if (type == 0) mode.total = contentLength;
                    InputStream is = response.body().byteStream();
                    int len, idx = 0;
                    long readTime = 0, time = 0;
                    byte[] buf = new byte[1024];
                    RandomAccessFile outputStream = new RandomAccessFile(mode.path, "rwd");
                    outputStream.seek(mode.currLen);//移动到读写位置
                    while ((len = is.read(buf)) > 0) {
                        if (isStop) break;
                        outputStream.write(buf, 0, len);
                        mode.currLen += len;
                        idx++;
                        if (idx % 50 == 0) {// 提示进度
                            idx = 0;
                            time = System.currentTimeMillis();
                            if (time - readTime > 200) {
                                if (downloadManage != null) downloadManage.inProgress(mode);
                            }
                            readTime = time;
                        }
                        if (isStop) break;
                    }
                    outputStream.close();
                    response.body().close();
                    is.close();
                    if (isStop) {// 取消或暂停
                        if (downloadManage != null) downloadManage.onStop(mode);
                    } else {// 下载完成
                        if (downloadManage != null) downloadManage.onResponse(mode);
                    }
                } else onFailure(null, null);
            } catch (Exception e) {
                if (Logger.isDebug) e.printStackTrace();
                onFailure(null, null);
            }
        }
    };
}
